<template>
  <div ref="mapContainer" class="map-container"></div>
</template>

<script>
import axios from "axios";
export default {
  data() {
    return {
      map: null,
      view: null,
      useWebGL: true, // Whether to use WebGL version
    };
  },
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    // 清理资源
    if (this.view) {
      this.view.destroy();
    }
    if (this.map) {
      this.map.destroy();
    }
  },
  methods: {
    // 检查浏览器WebGL支持情况
    checkWebGLSupport() {
      try {
        const canvas = document.createElement("canvas");
        const gl =
          canvas.getContext("webgl") || canvas.getContext("experimental-webgl");

        if (!gl) {
          console.warn("WebGL not supported, falling back to normal map");
          return false;
        }

        return true;
      } catch (e) {
        console.error("Error checking WebGL support:", e);
        return false;
      }
    },

    async initMap() {
      try {
        // 检查WebGL支持
        this.useWebGL = this.checkWebGLSupport();

        // 根据WebGL支持情况加载不同版本的API
        if (this.useWebGL) {
          console.log("使用WebGL版本地图");
          await this.loadScript(
            "https://api.map.baidu.com/api?v=1.0&type=webgl&ak=yFCr011v0WGwcosRqgVobH3boG4fhRiD"
          );
          await this.loadScript(
            "https://code.bdstatic.com/npm/mapvgl@1.0.0-beta.189/dist/mapvgl.min.js"
          );
          await this.loadScript(
            "https://code.bdstatic.com/npm/mapvgl@1.0.0-beta.189/dist/mapvgl.threelayers.min.js"
          );
        } else {
          console.log("使用非WebGL版本地图");
          await this.loadScript(
            "//api.map.baidu.com/api?v=3.0&ak=yFCr011v0WGwcosRqgVobH3boG4fhRiD"
          );
          await this.loadScript(
            "//api.map.baidu.com/library/Heatmap/2.0/src/Heatmap_min.js"
          );
        }

        console.log("地图API加载完成");

        // 初始化地图
        if (this.useWebGL) {
          this.map = new window.BMapGL.Map(this.$refs.mapContainer, {
            tilt: 0,
          });
        } else {
          this.map = new window.BMap.Map(this.$refs.mapContainer);
        }
       

        // 北京市中心，适合展示中国全图
        const point = this.useWebGL
          ? new window.BMapGL.Point(116.404, 39.915)
          : new window.BMap.Point(116.404, 39.915);

        this.map.centerAndZoom(point, 5); // 缩小缩放级别以便查看全国分布

        console.log("地图初始化完成");
        console.log(89787, this.map);
        // 添加控件
        if (this.useWebGL) {
          const zoomCtrl = new window.BMapGL.ZoomControl();
          this.map.addControl(zoomCtrl);
          const scaleCtrl = new window.BMapGL.ScaleControl();
          this.map.addControl(scaleCtrl);
          this.map.enableScrollWheelZoom();
        } else {
          const navCtrl = new window.BMap.NavigationControl();
          this.map.addControl(navCtrl);
          const scaleCtrl = new window.BMap.ScaleControl();
          this.map.addControl(scaleCtrl);
          this.map.enableScrollWheelZoom();
        }

        // 只有在WebGL模式下才初始化View
        if (this.useWebGL) {
          try {
            this.view = new window.mapvgl.View({
              effects: [
                new window.mapvgl.BloomEffect({
                  threshold: 0.2,
                  blurSize: 2.0,
                }),
              ],
              map: this.map,
            });
            console.log("View初始化完成");
          } catch (e) {
            console.error("View初始化失败，切换到非WebGL模式:", e);
            // 如果View初始化失败，切换到非WebGL模式
            this.useWebGL = false;
            // 重新加载地图
            this.$refs.mapContainer.innerHTML = "";
            return this.initMap();
          }
        }

        // 加载数据
        const data = await this.loadAlumniData();
        console.log("数据加载完成，准备绘制热力图");

        if (this.useWebGL) {
          this.drawWebGLHeatmap(data);
        } else {
          this.drawStandardHeatmap(data);
        }
      } catch (e) {
        console.error("地图初始化失败:", e);
        alert("地图初始化失败，请检查网络连接并刷新页面重试。");
      }
    },

    async loadAlumniData() {
      try {
        console.log("开始请求校友数据");
        // 获取所有校友数据用于地图显示
        const response = await axios.get("/Alumnus", {
          params: {
            id: "",
            name: "",
            username: "",
            gender: "",
            major: "",
            department: "",
            nativePlace: "",
            phone: "",
            email: "",
            page: 1,
            pageSize: 99999,
          },
        });
        console.log("获取到的数据:", response.data);
        if (response.data && response.data.data && response.data.data.rows) {
          console.log(`获取到${response.data.data.rows.length}条校友数据`);
          return response.data.data.rows;
        } else {
          console.error("数据格式不正确:", response.data);
          // 使用测试数据
          return this.getTestData();
        }
      } catch (error) {
        console.error("获取校友位置数据失败:", error);
        // 使用测试数据
        return this.getTestData();
      }
    },

    // 提供一些测试数据，确保热力图可以正常显示
    getTestData() {
      console.log("使用测试数据");
      return [
        {
          id: 1,
          latitude: 39.9042,
          longitude: 116.4074,
          name: "测试1",
          department: "测试院系",
          major: "测试专业",
        },
        {
          id: 2,
          latitude: 39.8335,
          longitude: 116.9889,
          name: "测试2",
          department: "测试院系",
          major: "测试专业",
        },
        {
          id: 3,
          latitude: 39.8386,
          longitude: 116.0833,
          name: "测试3",
          department: "测试院系",
          major: "测试专业",
        },
        {
          id: 4,
          latitude: 31.2304,
          longitude: 121.4737,
          name: "测试4",
          department: "测试院系",
          major: "测试专业",
        },
        {
          id: 5,
          latitude: 27.7517,
          longitude: 118.0322,
          name: "测试5",
          department: "测试院系",
          major: "测试专业",
        },
        // 再加几十个点形成热力区域
        ...Array(50)
          .fill()
          .map((_, i) => ({
            id: 6 + i,
            latitude: 39.9 + Math.random() * 0.1 - 0.05,
            longitude: 116.4 + Math.random() * 0.1 - 0.05,
            name: `热点${i + 1}`,
            department: "热点学院",
            major: "热点专业",
          })),
      ];
    },

    // WebGL版热力图绘制
    drawWebGLHeatmap(alumniData) {
      console.log("开始绘制WebGL热力图，原始数据:", alumniData);

      // 过滤掉没有经纬度的数据
      const validData = alumniData.filter(
        (alumni) =>
          alumni &&
          alumni.latitude != null &&
          alumni.longitude != null &&
          !isNaN(parseFloat(alumni.latitude)) &&
          !isNaN(parseFloat(alumni.longitude))
      );

      console.log(
        `总数据: ${alumniData.length}, 有效数据: ${validData.length}`
      );
      console.log("有效数据示例:", validData.slice(0, 2));

      if (validData.length === 0) {
        console.error("没有有效的地理位置数据，无法绘制热力图");
        alert("没有有效的地理位置数据，无法绘制热力图");
        return;
      }

      // 转换数据格式以适应热力图
      const data = validData.map((alumni) => {
        const item = {
          geometry: {
            type: "Point",
            coordinates: [
              parseFloat(alumni.longitude),
              parseFloat(alumni.latitude),
            ],
          },
          properties: {
            count: 80, // 增加每个点的权重值，使热力图更明显
            name: alumni.name || `校友#${alumni.id}`,
            department: alumni.department || "未填写",
            major: alumni.major || "未填写",
            gender:
              alumni.gender === 1 ? "男" : alumni.gender === 2 ? "女" : "未知",
            id: alumni.id,
          },
        };
        return item;
      });

      console.log("转换后的数据:", data.slice(0, 2));

      // 创建热力图层
      const heatLayer = new window.mapvgl.HeatPointLayer({
        size: 25, // 增加热力点大小
        blend: "lighter",
        min: 0,
        max: 100,
        // 调整颜色渐变以匹配示例图片（黄色-橙色渐变）
        gradient: {
          0.0: "rgba(0, 0, 0, 0.0)",
          0.1: "rgba(30, 30, 30, 0.5)",
          0.2: "rgba(50, 50, 20, 0.6)",
          0.3: "rgba(80, 80, 0, 0.7)",
          0.4: "rgba(120, 120, 0, 0.8)",
          0.5: "rgba(150, 150, 0, 0.85)",
          0.6: "rgba(180, 180, 0, 0.9)",
          0.7: "rgba(210, 200, 0, 0.95)",
          0.8: "rgba(250, 220, 0, 1.0)",
          0.9: "rgba(255, 240, 0, 1.0)",
          1.0: "rgba(255, 255, 0, 1.0)",
        },
      });

      console.log("热力图层创建完成");

      // 存储Vue实例的this引用
      const vm = this;

      // 添加点图层，显示具体校友分布
      const pointLayer = new window.mapvgl.PointLayer({
        blend: "normal",
        size: 8,
        color: "#FFD700", // 金色点
        enablePicked: true, // 启用点选中
        onPicked(e) {
          if (e.type === "click") {
            const properties = e.dataItem.properties;
            const content = `
              <div style="padding: 10px; color: #333;">
                <h3 style="margin: 0 0 10px 0;">${properties.name}</h3>
                <p style="margin: 5px 0;">ID: ${properties.id}</p>
                <p style="margin: 5px 0;">性别: ${properties.gender}</p>
                ${
                  properties.department !== "未填写"
                    ? `<p style="margin: 5px 0;">学院: ${properties.department}</p>`
                    : ""
                }
                ${
                  properties.major !== "未填写"
                    ? `<p style="margin: 5px 0;">专业: ${properties.major}</p>`
                    : ""
                }
              </div>
            `;
            const infoWindow = new window.BMapGL.InfoWindow(content, {
              width: 250,
              height: 150,
              title: "校友信息",
            });
            const point = new window.BMapGL.Point(
              e.dataItem.geometry.coordinates[0],
              e.dataItem.geometry.coordinates[1]
            );
            vm.map.openInfoWindow(infoWindow, point);
          }
        },
      });

      console.log("点图层创建完成，添加到地图");

      this.view.addLayer(heatLayer);
      this.view.addLayer(pointLayer);

      console.log("设置图层数据");
      heatLayer.setData(data);
      pointLayer.setData(data);

      console.log("数据设置完成，准备调整视图");

      // 调整视图
      if (data.length > 0) {
        console.log("调整视图以显示所有点");
        // 计算所有点的边界
        const bounds = new window.BMapGL.Bounds();
        data.forEach((item) => {
          bounds.extend(
            new window.BMapGL.Point(
              item.geometry.coordinates[0],
              item.geometry.coordinates[1]
            )
          );
        });
        // 设置地图视图以包含所有点
        this.map.setViewport(bounds);
        console.log("视图调整完成");
      }
    },

    // 标准版热力图绘制（非WebGL）
    drawStandardHeatmap(alumniData) {
      console.log("开始绘制标准热力图，原始数据:", alumniData);

      // 过滤掉没有经纬度的数据
      const validData = alumniData.filter(
        (alumni) =>
          alumni &&
          alumni.latitude != null &&
          alumni.longitude != null &&
          !isNaN(parseFloat(alumni.latitude)) &&
          !isNaN(parseFloat(alumni.longitude))
      );

      console.log(
        `总数据: ${alumniData.length}, 有效数据: ${validData.length}`
      );

      if (validData.length === 0) {
        console.error("没有有效的地理位置数据，无法绘制热力图");
        alert("没有有效的地理位置数据，无法绘制热力图");
        return;
      }

      // 转换数据为普通热力图格式
      const points = validData.map((alumni) => {
        return {
          lng: parseFloat(alumni.longitude),
          lat: parseFloat(alumni.latitude),
          count: 80, // 增加热力值
        };
      });

      // 创建普通版热力图实例
      const heatmapOverlay = new window.BMapLib.HeatmapOverlay({
        radius: 25,
        gradient: {
          0.1: "rgb(30, 30, 30)",
          0.3: "rgb(80, 80, 0)",
          0.5: "rgb(150, 150, 0)",
          0.7: "rgb(210, 200, 0)",
          0.9: "rgb(255, 240, 0)",
          1.0: "rgb(255, 255, 0)",
        },
      });
      this.map.addOverlay(heatmapOverlay);
      heatmapOverlay.setDataSet({
        data: points,
        max: 100,
      });

      // 添加点标记和信息窗口
      const vm = this;
      validData.forEach((alumni) => {
        const point = new window.BMap.Point(
          parseFloat(alumni.longitude),
          parseFloat(alumni.latitude)
        );
        const marker = new window.BMap.Marker(point);
        this.map.addOverlay(marker);

        // 添加点击事件
        marker.addEventListener("click", function () {
          const name = alumni.name || `校友#${alumni.id}`;
          const gender =
            alumni.gender === 1 ? "男" : alumni.gender === 2 ? "女" : "未知";
          const department = alumni.department || "未填写";
          const major = alumni.major || "未填写";

          const content = `
            <div style="padding: 10px; color: #333;">
              <h3 style="margin: 0 0 10px 0;">${name}</h3>
              <p style="margin: 5px 0;">ID: ${alumni.id}</p>
              <p style="margin: 5px 0;">性别: ${gender}</p>
              ${
                department !== "未填写"
                  ? `<p style="margin: 5px 0;">学院: ${department}</p>`
                  : ""
              }
              ${
                major !== "未填写"
                  ? `<p style="margin: 5px 0;">专业: ${major}</p>`
                  : ""
              }
            </div>
          `;

          const infoWindow = new window.BMap.InfoWindow(content, {
            width: 250,
            height: 150,
            title: "校友信息",
          });
          vm.map.openInfoWindow(infoWindow, point);
        });
      });

      // 调整视图
      if (points.length > 0) {
        // 计算所有点的边界
        const boundsArr = points.map((point) => {
          return new window.BMap.Point(point.lng, point.lat);
        });
        // 设置地图视图以包含所有点
        this.map.setViewport(boundsArr);
      }
    },

    loadScript(src) {
      return new Promise((resolve, reject) => {
        const script = document.createElement("script");
        script.src = src;
        script.onload = resolve;
        script.onerror = reject;
        document.head.appendChild(script);
      });
    },
  },
};
</script>

<style>
.map-container {
  width: 100%;
  height: 100vh;
  margin: 0;
  padding: 0;
}
</style>
